/*
 * Copyright (c) 2009 LastFM.Desktop Anton Pavlik.
 * All Rights Reserved.
 * 
 * You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, 
 * with or without modifications, and in Source or Object form, provided that You meet the following 
 * conditions:
 * 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
 *
 * 2. You must cause any modified files to carry prominent notices stating that You changed the files; 
 * and
 *
 * 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, 
 * patent, trademark, and attribution notices from the Source form of the Work, excluding those notices 
 * that do not pertain to any part of the Derivative Works.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, Licensor provides the Work 
 * (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties 
 * or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. 
 * YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE WORK
 * AND ASSUME ANY RISKS ASSOCIATED WITH YOUR EXERCISE OF PERMISSIONS UNDER THIS LICENSE. 
 */
package org.shake.lastfm.ui.artist;

import java.awt.BorderLayout;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.swing.JScrollPane;
import javax.swing.SwingWorker;
import javax.swing.UIManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventTopicSubscriber;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXPanel;
import org.shake.lastfm.api.XmlRpcApi;
import org.shake.lastfm.api.XmlRpcApiImpl;
import org.shake.lastfm.event.EventTopic;
import org.shake.lastfm.event.TrackSelectedEvent;
import org.shake.lastfm.model.Picture;
import org.shake.lastfm.model.Track;
import org.shake.lastfm.model.Picture.PictureSize;

public class ArtistPicturesPanel extends JXPanel
{
    private static final long serialVersionUID = -3585158960256978714L;
    private Track selectedTrack;
    
    private JXList imagesList;
    private ArtistImagesListModel listModel;
    
    private SwingWorker<List<Picture>, Void> picturesFetcher;

    public ArtistPicturesPanel()
    {
        super();
        
        buildUI();
        
        AnnotationProcessor.process(this);
    }

    private void buildUI()
    {
        this.listModel = new ArtistImagesListModel();
        
        this.imagesList = new JXList(this.listModel);
        this.imagesList.setVisibleRowCount(0);
        this.imagesList.setLayoutOrientation(JXList.HORIZONTAL_WRAP);
        this.imagesList.setCellRenderer(new ArtistImageCellRenderer(PictureSize.LARGE));
        this.imagesList.setBackground(UIManager.getColor("Label.background"));
        this.imagesList.setOpaque(false);
        
        setLayout(new BorderLayout());
        add(new JScrollPane(this.imagesList));
    }

    @EventTopicSubscriber(topic=EventTopic.TRACK_SELECTED)
    public void onTrackSelectionChanged(String topic, TrackSelectedEvent event)
    {
        this.selectedTrack = event.getTrack();
        
        if (this.picturesFetcher != null && !this.picturesFetcher.isDone())
        {
            this.picturesFetcher.cancel(true);
        }

        if (this.selectedTrack != null)
        {
            this.picturesFetcher = new PicturesFetcher(this.selectedTrack.getCreator());
            this.picturesFetcher.execute();
        }
    }
    
    private void addPictures(List<Picture> pictures)
    {
        this.imagesList.getSelectionModel().clearSelection();
        this.listModel.set(pictures);
    }
    
    private class PicturesFetcher extends SwingWorker<List<Picture>, Void>
    {
        private final String artistName;
        private Log log = LogFactory.getLog(PicturesFetcher.class);

        public PicturesFetcher(String artistName)
        {
            this.artistName = artistName;
        }
        @Override
        protected List<Picture> doInBackground() throws Exception
        {
            XmlRpcApi api = new XmlRpcApiImpl();
            return api.fetchArtistPictures(this.artistName);
        }
        
        @Override
        protected void done()
        {
            List<Picture> list;
            try
            {
                list = get();
                addPictures(list);
            } catch (InterruptedException e)
            {
                log.info(e.getMessage());
            } catch (ExecutionException e)
            {
                log.info(e.getMessage());
            }
        }
    }
}